<?php


namespace app\repository\Device\Room;


use app\Enums\GamesStatus;
use app\Enums\LogChannel;
use app\model\ApiUser;
use app\model\Games;
use app\model\GamesCard;
use app\model\GamesRecord;
use app\model\Logs;
use app\model\RoomDevice;
use app\model\WxUser;
use app\repository\Repository;
use Carbon\Carbon;
use support\Cache;
use support\Db;

class RoomDeviceRepository extends Repository
{





    public function ready($username)
    {
        $user = ApiUser::query()->with(["room"])->where("username", $username)->first();
        if (!$user){
            return $this->error("系统查找不到您的参数");
        }
        if (!$user->room){
            return $this->error("您登录的账号不允许进行此操作");
        }
        $udpIp = $user->room->udp_ip;
        $var = Cache::get("$udpIp-bind");
        if (!$var){
            return $this->error("您的队伍已经销毁，请重新刷手环",303);
        }
        $gameItem = json_decode($var, true);
        if (!$gameItem){
            return $this->error("您的队伍已经销毁，请重新刷手环",303);
        }
        $deviceId = self::getCardNo();
        $beginTime = Carbon::now()->toDateTimeString();
        $game = [
            "device_id"=>$deviceId,
            "status"=>GamesStatus::READY,
            "begin_time"=>$beginTime,
        ];
        DB::beginTransaction();
        try {


            $model = Games::query()->create($game);
            foreach ($gameItem["list"] as &$item){
                unset($item["own_time"]);
                $item["device_id"] = $deviceId;
                $item["begin_time"] = $beginTime;
                $item["game_id"] = $model->id;
            }
            GamesCard::insert($gameItem["list"]);
//            dump($user->room->game_key,$deviceId,$user->room->tcp_key,120);
            $this->getTcpServer()->readyGame($user->room->game_key,$deviceId,$user->room->tcp_key,120);
            Cache::set("$udpIp-bind","");
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            dump($exception->getTraceAsString(),$exception->getMessage());
            $this->createLogs(LogChannel::READY_GAME,
                json_encode([
                    "game_item"=>$gameItem,
                    "game"=>$game,
                    "room"=>$user->room
                ]),
                $exception->getMessage(),
                $exception->getTraceAsString()
            );
//            Logs::query()->create([
//                "channel"=> LogChannel::READY_GAME,
//                "input_data"=>json_encode([
//                    "game_item"=>$gameItem,
//                    "game"=>$game,
//                    "room"=>$user->room
//                ],
//                "content
//            )]);
            return $this->error("系统错误");
        }
        return $this->ok();
    }

    public function get()
    {

    }

    public function init_user($username, $ip)
    {
        $apiUser = ApiUser::query()->with(["room"])->where("username", $username)->first();
        if (!$apiUser){
            return $this->error("您的账户不对");
        }
        $room = RoomDevice::query()->where("outside_pc_ip", $ip)->first();
        if (!$room){
            return $this->error("您的局域网 ip 不是对应房间");
        }
        if ($room->id != $apiUser->room_id){
            return $this->error("房间账户与本机 ip未对应");
        }
        $udpIp = $room->udp_ip;
        $var = Cache::get("$udpIp-bind");
        if ($var){
            $gameItem = json_decode($var, true);
            $userIdList = array_column($gameItem["list"], "user_id");
            $collection = WxUser::query()->whereIn("id", $userIdList)->get();
            return $this->success([
                "list"=>$collection->toArray(),
                "created_at" =>$gameItem["created_at"]
            ]);
        }
        return $this->success([]);

    }

}